#include "signal_processor.h"

// 计算信号功率 (dB)
float SignalProcessor::computePowerDB(const Complex &sample)
{
    return 10.0f * std::log10(std::norm(sample) + 1e-12f);
}

// 计算信号功率 (线性)
float SignalProcessor::computePowerLinear(const Complex &sample)
{
    return std::norm(sample);
}

// 计算幅度
float SignalProcessor::computeMagnitude(const Complex &sample)
{
    return std::abs(sample);
}

// 计算相位
float SignalProcessor::computePhase(const Complex &sample)
{
    return std::arg(sample);
}

// 汉宁窗
std::vector<float> SignalProcessor::hanningWindow(int size)
{
    std::vector<float> window(size);
    for (int i = 0; i < size; ++i)
    {
        window[i] = 0.5f * (1.0f - std::cos(2.0f * M_PI * i / (size - 1)));
    }
    return window;
}

// 应用窗函数
void SignalProcessor::applyWindow(std::vector<Complex> &data, const std::vector<float> &window)
{
    for (size_t i = 0; i < data.size(); ++i)
    {
        data[i] *= window[i];
    }
}

// 快速傅里叶变换 (使用FFTW库)
void SignalProcessor::fft(std::vector<Complex> &data)
{
    int n = data.size();
    fftwf_complex *in = reinterpret_cast<fftwf_complex *>(data.data());
    fftwf_complex *out = reinterpret_cast<fftwf_complex *>(data.data());

    fftwf_plan plan = fftwf_plan_dft_1d(n, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
    fftwf_execute(plan);
    fftwf_destroy_plan(plan);
}

// 快速傅里叶逆变换
void SignalProcessor::ifft(std::vector<Complex> &data)
{
    int n = data.size();
    fftwf_complex *in = reinterpret_cast<fftwf_complex *>(data.data());
    fftwf_complex *out = reinterpret_cast<fftwf_complex *>(data.data());

    fftwf_plan plan = fftwf_plan_dft_1d(n, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);
    fftwf_execute(plan);
    fftwf_destroy_plan(plan);

    // 归一化
    for (int i = 0; i < n; ++i)
    {
        data[i] /= static_cast<float>(n);
    }
}

// 二维FFT
void SignalProcessor::fft2d(MatrixXcf &data)
{
    int rows = data.rows();
    int cols = data.cols();

    // 对每行进行FFT
    for (int i = 0; i < rows; ++i)
    {
        std::vector<Complex> row_vec(cols);
        for (int j = 0; j < cols; ++j)
        {
            row_vec[j] = data(i, j);
        }
        fft(row_vec);
        for (int j = 0; j < cols; ++j)
        {
            data(i, j) = row_vec[j];
        }
    }

    // 对每列进行FFT
    for (int j = 0; j < cols; ++j)
    {
        std::vector<Complex> col_vec(rows);
        for (int i = 0; i < rows; ++i)
        {
            col_vec[i] = data(i, j);
        }
        fft(col_vec);
        for (int i = 0; i < rows; ++i)
        {
            data(i, j) = col_vec[i];
        }
    }
}